<!--
 * @Author: 周艳凯 484894717@qq.com
 * @Date: 2025-03-17 15:32:58
 * @LastEditors: 周艳凯 484894717@qq.com
 * @LastEditTime: 2025-04-11 20:43:35
 * @FilePath: \BusStopBoard.Webd:\360MoveData\Users\75041\Desktop\uniapp框架\my-project\src\pages\index\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
	<view class="content w-full" id="contractimage4">
		<Navigatio></Navigatio>
		<!-- 轮播图组件 -->
		<swiperComs></swiperComs>
		<!-- 滚动通知 -->
		<tnoticBar></tnoticBar>
		<view class="tool" @click="morestps" v-if="getlineNode.length > 4">
			<view class="to-box"> 查询线路导航请点击 </view>
		</view>
		<lineoin></lineoin>
	</view>
</template>

<script>
import { getitemlistbydevsn, uploadShotFile } from '@/api/common/user/user';
import WebSocketClient from './websock'
import Navigatio from './modules/Navigatio.vue';
import swiperComs from './swiper.vue'
import linesda from './line.vue'
import tnoticBar from './tnoticBar.vue'
import lineoin from './line/index.vue'
const imageExtensions = new Set(['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']);
const videoExtensions = new Set(['mp4', 'avi', 'mov', 'mkv', 'flv', 'webm']);
export default {
	components: {
		swiperComs,
		Navigatio,
		tnoticBar,
		linesda,
		lineoin,
	},
	data() {
		return {
			intervalId: null,
		}
	},
	computed: {
		getlineNode() {
			return this.$store.getters.getlineNode;
		}
	},
	onBackPress(options) {
		// 点击虚拟键或者侧滑的时候触发（不允许返回）
		if (options.from === 'backbutton') {
			return true
		}
		// 否则则允许返回
		return false;
	},
	onLoad() {

	},
	mounted() {
		// 获取webscok
		// this.initWebsock()
		this.initWebsock()
		// 每小时拉取下数据看看是否有更新
		const THIRTY_MINUTES = 30 * 60 * 1000 // 更易读的时间单位
		this.intervalId = setInterval(() => {
			this.initImg()
		}, THIRTY_MINUTES)
	},
	methods: {
		initWebsock() {
			const socketWBObj = new WebSocketClient(`${this.$store.state.apiUrl}/hubs/device?DevSn=${this.$store.state.androidId}`)
			// 连接WebSocket
			socketWBObj.connect();
			// 接收消息时触发
			socketWBObj.onMessage = (msgData) => {
				console.log(msgData,'我监听到2次数据老弟')
				try {
					if (msgData.type === 1 && msgData.target == "ReceiveMessage") {
						if (msgData.arguments[0].lineIds == 'Text' || msgData.arguments[0].lineIds == 'Clear') {
							this.$store.commit('changePushText', msgData.arguments[0]);
							return
						}
						if (msgData.arguments[0].lineIds == 'Shot') {
							this.downloadFile()
							return
						}
						this.$store.commit('SET_receiveUserName', msgData.arguments[0]);
					}
				} catch (error) {
					console.log(error)
				}
			}
		},
		morestps: function () {
			uni.navigateTo({
				url: '/pages/poput/index',
			});
		},
		// 加载图片资源
		async initImg() {
			// 获取轮播图
			await getitemlistbydevsn({
				DevSN: this.$store.state.androidId,
			})
				.then(async (res) => {
					console.warn(res, '我是循环轮播数据')
					const imageList = this.$store.getters.getswiperList

					// 合并 video 和 picture 数组
					let combinedMedia = [
						...(res.data.result.picture || []),
						...(res.data.result.video || [])];
					combinedMedia = combinedMedia.map(item => {
						item.fileUrl = item.content
						return item
					})

					this.$store.commit('changetextArray', res.data.result?.text || [])
					// 获取本地存储的图片
					const flog = this.isSameNames(imageList, combinedMedia)
					// // 如果是true代表已经不需要更新 反之需要更新
					// console.log('我要开始更新了')
					if (flog) {
						console.log('不需要更新');
					} else {
						console.log('我要更新')
						// #ifdef APP-PLUS
						const results = await this.getSavedFileList()
						this.$store.commit('changeSwiper', [])
						console.log('清理成功我先执行', results)
						// #endif                     
						if (!res.data.result) {
							return this.$store.commit('changeSwiper', [])
						}
						const downloadTasks = combinedMedia.map(async (item, index) => {
							// 获取文件扩展名
							const extension = this.getExtension(item.fileUrl);
							if (!extension) return false;
							const params = {
								type: '',
								src: '',
								id: index,
								fileUrl: item.fileUrl
							};
							if (imageExtensions.has(extension)) {
								params.type = 'image';
							} else if (videoExtensions.has(extension)) {
								params.type = 'video';
							}
							const url = `${this.$store.state.apiUrl}/${item.fileUrl}`;
							console.log(url, '我是图片地址')

							// #ifdef APP-PLUS
							const savedPath = await this.downloadAndSave(url);
							// #endif 
							// #ifdef H5
							const savedPath = url
							// #endif 
							params.src = savedPath;
							return params;
						});
						// 4. 过滤失败项并存储
						const result = await Promise.all(downloadTasks)
						console.log(result, '我是更新后的轮播图地地址')
						this.$store.commit('changeSwiper', result)
					}
				})
				.catch((error) => {
					console.log(error, '我是轮播图失败了');
					// uni.showToast({
					// 	title: '轮播图更新失败' + error,
					// 	icon: 'none',
					// 	duration: 10000,
					// });
				});
		},
		getExtension(filename) {
			const match = filename.match(/\.([^.]+)$/);
			return match ? match[1].toLowerCase() : null;
		},
		isSameNames(arr1, arr2) {
			// 简化 null/undefined 检查
			if (arr1 == null || arr2 == null) return false;
			// 确保类型为数组
			if (!Array.isArray(arr1) || !Array.isArray(arr2)) return false;
			// 长度不等直接返回
			if (arr1.length !== arr2.length) return false;
			// 提取并排序 fileUrl 数组
			const getSortedUrls = (arr) => arr.map(item => item.fileUrl).sort();

			const names1 = getSortedUrls(arr1);
			const names2 = getSortedUrls(arr2);

			// 逐元素比较提升性能
			return names1.every((value, index) => value === names2[index]);
		},
		/**
		 * 获取本地保存的文件列表
		 * @returns {Promise<Array>} 包含文件信息的数组
		 */
		async getSavedFileList() {
			try {
				// 1. Promise 化获取文件列表
				const fileRes = await new Promise((resolve) => {
					uni.getSavedFileList({
						success: resolve,
						fail: err => resolve({ errMsg: err.errMsg }) // 错误也转为 resolve
					});
				})
				// 2. 处理获取列表失败或空列表的情况
				if (fileRes.errMsg !== 'getSavedFileList:ok') {
					return { success: false, error: '获取文件列表失败', detail: fileRes };
				}
				if (!fileRes.fileList?.length) {
					return { success: true, message: '无缓存文件' };
				}
				// 3. 并行删除所有文件（兼容失败）
				const deleteResults = await Promise.all(
					fileRes.fileList.map(file =>
						new Promise(resolve => {
							uni.removeSavedFile({
								filePath: file.filePath,
								complete: (res) => {
									// 统一返回结构：成功时 error 为 null
									resolve(res.errMsg === 'removeSavedFile:ok' ?
										{ success: true, filePath: file.filePath } :
										{ success: false, filePath: file.filePath, error: res }
									);
								}
							});
						})
					)
				);
				// 4. 统计操作结果
				const errors = deleteResults.filter(v => !v.success);
				return {
					success: errors.length === 0,
					deletedCount: deleteResults.length - errors.length,
					errors: errors,
					message: errors.length ?
						`删除了 ${deleteResults.length - errors.length} 个文件，${errors.length} 个失败` :
						'所有文件删除成功'
				};
			} catch {
				return {
					success: false,
					error: '未知异常',
					detail: error
				};
			}
		},
		// 下载并保存文件
		async downloadAndSave(url) {
			try {
				// 下载阶段（使用await保证顺序执行）
				const { tempFilePath } = await new Promise((resolve, reject) => {
					uni.downloadFile({
						url,
						success: (res) => {
							if (res.statusCode === 200) {
								resolve(res)
							} else {
								reject(new Error(`下载失败，状态码：${res.statusCode}`))
							}
						},
						fail: reject
					})
				})

				// 持久化存储阶段
				const { savedFilePath } = await new Promise((resolve, reject) => {
					uni.saveFile({
						tempFilePath,
						success: resolve,
						fail: reject
					})
				})

				return savedFilePath

			} catch (error) {
				// 统一错误处理（不会向上抛出异常）
				console.error('[文件操作]', error.message)
				return null // 返回null而不是undefined更符合规范
			}
		},
		showLoading() {
			console.log("加载中")
			uni.showLoading({
				title: '加载中……',
				mask: true
			})
		},
		hideLoading() {
			uni.hideLoading()
		},
		renderFinish(opt) {
			console.log("生成完成", opt)
			// 获取到图片地址（base64）
			// DoSomeThing ……
			this.hideLoading()

			const params = {
				fileName: this.$store.state.androidId,
				fileDataBase64: opt.path,
			}

			uploadShotFile(params).then(res => {
				console.log(res, '我是截图的图片地址')
			})
		},
		// 保存截图
		downloadFile() {
			const that = this
			var pages = getCurrentPages();
			var page = pages[pages.length - 1];
			var bitmap = null;
			var currentwebview = page.$getAppWebview();
			// 创建bitmap对象
			bitmap = new plus.nativeObj.Bitmap('amway_img');
			// 将webview内容绘制到bitmap对象中
			currentwebview.draw(bitmap, function () {
				// 生成随机文件名，避免图片被覆盖
				// let rand = Math.floor(Math.random() * 10000);
				let saveUrl = '_doc/' + 'jieping' + 'a.jpg';

				// 保存bitmap对象为图片文件
				bitmap.save(saveUrl, {}, function (i) {
					console.log('保存图片成功:' + JSON.stringify(i));
					console.log(i.target, '我是i啊帖子')

					plus.io.resolveLocalFileSystemURL(i.target, (entry) => {
						// 可通过entry对象操作test.html文件 
						entry.file((file) => {
							let fileReader = new plus.io.FileReader();
							fileReader.onloadend = (evt) => {
								try {
									const base64 = evt.target.result.substr(22);
									const imgBase64URL = 'data:image/png;base64' + base64
									const params = {
										fileName: that.$store.state.androidId,
										fileDataBase64: imgBase64URL,
									}
									uploadShotFile(params).then(res => {
										console.log(res, '我是截图的图片地址')
									})
								} catch (error) {
									console.log(error, '我宝错了')
								}

							}
							fileReader.readAsDataURL(file);
						});
					}, (e) => {
						alert("Resolve file URL failed: " + e.message);
					})

					// 将图片转成base64图片

					// 将图片保存到相册
					// uni.saveImageToPhotosAlbum({
					// 	filePath: i.target,
					// 	success: function () {
					// 		uni.showToast({
					// 			title: '截图成功',
					// 			duration: 1500
					// 		});
					// 	},
					// 	complete: function () {
					// 		uni.hideLoading();
					// 	}
					// });
				}, function (e) {
					console.log('保存图片失败:' + JSON.stringify(e));
				});
			}, function (e) {
				console.log('截屏绘制图片失败:' + JSON.stringify(e));
			});
		}
	}
}
</script>


<style lang="scss" scoped>
.content {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background: #000;
	// text-align: center;
}



::v-deep .u-notice-bar {
	height: 100%;
}

::v-deep .u-notice {
	height: 100%;
}

::v-deep .u-notice__swiper {
	height: 100%;
}


.tool {
	width: 100%;
	padding: 4rpx 4rpx;
	background: #00023d;

	.to-box {
		height: 42rpx;
		font-size: 20rpx;
		line-height: 42rpx;
		color: #ffffff;
		background: #68a1fb;
		border-radius: 10rpx;
		text-align: center;
	}
}
</style>
